import { Service } from "egg";
import { DepartmentProps } from "../model/Department";
import { Types } from "mongoose";

export default class DepartmentService extends Service {
  /**
   * 按需查询
   */
  public findByName(department_name: string) {
    return this.ctx.model.Department.findOne({ department_name });
  }

  /**
   * 查找列表
   */
  public async findList() {
    const { ctx } = this;
    // TODO 暂时写死公司ID，后续需要从ctx.state.user获取
    const { user: userInfo } = ctx.state;
    const list = await ctx.model.Department.find().lean();
    // console.log(list);
    // return list;
    return ctx.helper.listToTree(list, userInfo.company);
  }

  /**
   * 添加数据
   * @param data 测试数据
   */
  public async add(data) {
    const { ctx } = this;
    // TODO 暂时写死公司ID，后续需要从ctx.state.user获取
    const { user: userInfo } = ctx.state;
    const _data: Partial<DepartmentProps> = {
      ...data,
      company_id: Types.ObjectId(userInfo.company),
      ...(!data.parent_id && { parent_id: Types.ObjectId(userInfo.company) }),
    };
    return await ctx.model.Department.create(_data);
  }
}
